package com.hc.bank.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hc.bank.services.AccountServices;
import com.hc.bank.services.AccountServicesImpl;
import com.hc.bank.util.MyCon;

public class AccountServlet extends HttpServlet {

	private static final long serialVersionUID = 378663682612203345L;

	/*
	 * 1. 一个请求一个Servlet
	 * 
	 * 2. 一张表 对应一个Servet，对应一个Services，对应一个POJO，一个DAO
	 * 如果业务复杂情况下可以有多个Services，多个Dao，多个Servlet
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 账户servlet 可能需要处理多个业务请求
		/*
		 * 1. 区分那个业务请求 约定Action变量是用来区分不同的业务请求
		 */
		String action = request.getParameter("action");
		AccountServices accountServices = new AccountServicesImpl();

		if ("login".equals(action)) {
			// 用户请求 的是 登录
			String loginAccount = request.getParameter("loginAccount");
			String loginPwd = request.getParameter("loginPwd");
			Map<String, Object> map = accountServices.findUserLogin(loginAccount, loginPwd);

			// 判断是否登录成功：
			if (map.isEmpty()) {
				// 登录失败
				request.setAttribute("errorMsg", "账号或者密码错误 ！");

				request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
			} else {
				// 登录成功
				request.getSession().setAttribute(MyCon.USERINFO, map);
				/*
				 * 当前数据如果需要在多个页面，或者多个请求中获取，就需要保存值在session
				 * 如果只需在当前页面或当前请求中展示，就保存在request中
				 */
				response.sendRedirect("jsp/index.jsp");
			}
		} else if ("exit".equals(action)) {
			// 用户请求的是 退出
			request.getSession().removeAttribute(MyCon.USERINFO);
			response.sendRedirect("jsp/login.jsp");
		} else if ("updatePwd".equals(action)) {
			// 用户请求的是 修改 密码

		}

	}

}
